import WebsocketClass from '@utils/websocket'
import { getWebsocketOrigin } from '@utils'
import { WebsocketMapping } from '@enums'
import { WEBSOCKET_TYPE } from '@enums/websocket'

export const useWebsocketStore = defineStore('websocket', {
  state: () => ({
    response: null,
    socket: null
  }),
  getters: {},
  actions: {
    /**
     * 初始化websocket
     */
    init() {
      console.log('🌐 WebSocket Store 初始化开始')
      if (!this.socket) {
        const authStore = useAuthStore()
        const token = authStore?.token
        // 如果没有 token，不初始化 WebSocket
        if (!token) {
          console.warn('🌐 WebSocket 初始化失败: 未找到 token')
          return
        }
        
        const wsOrigin = getWebsocketOrigin()
        
        // 直接使用 WebsocketMapping.WEBSOCKET
        const wsPath = WebsocketMapping.WEBSOCKET
        console.log('🌐 WebSocket Path:', wsPath)
        
        const url = `${wsOrigin}${wsPath}/${token}`
        
        
        try {
          this.socket = new WebsocketClass(url, data => {
            // 根据消息类型打印不同的日志，但不打印具体消息内容
            if (data && data.type === WEBSOCKET_TYPE.HEARTBEAT) {
              console.log('🌐 WebSocket 收到心跳消息')
              return
            }
            
            // 查找消息类型名称
            const typeEntry = Object.entries(WEBSOCKET_TYPE).find(([_, value]) => value === data.type)
            const typeName = typeEntry ? typeEntry[0] : '未知类型'
            
            console.log(`🌐 WebSocket 收到 ${typeName}(${data.type}) 类型的消息`)
            this.response = data
          })
          this.socket.connect()
        } catch (error) {
          console.error('🌐 WebSocket 初始化错误:', error)
          this.socket = null
        }
      } else {
        console.log('🌐 WebSocket 已经初始化')
      }
    },
    /**
     * 发送信息
     * @param {*} data
     */
    send(params) {
      if (!this.socket) {
        console.warn('🌐 WebSocket 未初始化，无法发送消息')
        return
      }
      this.socket.send(params)
    },
    /**
     * 手动断开websocket
     */
    close() {
      if (this.socket) {
        this.socket.close()
      }
      this.response = null
      this.socket = null
    }
  }
})
